/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package exatrez.stripes.action;

import able.stripes.AbleActionBean;
import com.google.inject.Inject;
import exatrez.dao.DocumentDAO;
import exatrez.model.Document;

import exatrez.stripes.Configuration;
import java.io.File;
import java.io.FileInputStream;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ErrorResolution;
import net.sourceforge.stripes.action.HttpCache;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.UrlBinding;

/**
 *
 * @author fikri
 */
@HttpCache(allow = true)
@UrlBinding("/dokumen/view/{idDokumen}")
public class ViewDocumentAction extends AbleActionBean{
    
    private Integer idDokumen;
    
    @Inject
    private Configuration conf;
    
    @Inject private DocumentDAO documentDAO;
    
    public Integer getIdDokumen() {
        return idDokumen;
    }

    public void setIdDokumen(Integer id) {
        this.idDokumen = id;
    }
    
    @DefaultHandler
    public Resolution view() {
        if (idDokumen == 0) {
            return new ErrorResolution(500, "No Document provided!");
        }

        Document d = documentDAO.findById(idDokumen);
        if (d == null) {
            return new ErrorResolution(500, "Document no found!!");
        }

        String docPath = conf.getProperty("document.path");
        if (docPath == null) {
            return new ErrorResolution(500,
                    "Configuration of \"document.path\" cant be found!!");
        }
        
        String path = docPath + (docPath.endsWith(File.separator) ? "" : File.separator) 
                + d.getDocumentPath();
        
        File f = new File(path);   
        FileInputStream fis = null;
        try{
            fis = new FileInputStream(f);
        } catch (Exception ex) {
        }

//        getContext().getResponse().setContentType("application/octet-stream" );
        getContext().getResponse().setContentType(d.getContentType());

        return new StreamingResolution(d.getContentType(), fis).setFilename(d.getTitle());

    }
    
}
